import { Table, Tag, Card, Form, Button, Input, Modal, message, Row, Col, Checkbox, Radio } from 'antd'
import { useStore } from '@/store'
import { useEffect, useState } from 'react'
import { http } from '@/utils'
const { TextArea } = Input

const Setvariety = (props) => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [featureText, setFeatureText] = useState('')
  const [mark, setMark] = useState('')
  const handleOk = () => {
    form.resetFields()
    setTagList([])
    setSelectedRowKeys([])
    setParams({
      pageNum: 1,
      pageSize: 20
    })
    props.changeVarietyModal(false)
  }
  const handleCancel = () => {
    form.resetFields()
    setTagList([])
    setSelectedRowKeys([])
    setParams({
      pageNum: 1,
      pageSize: 20
    })
    props.changeVarietyModal(false)
  }
  const [exchangeIdOpt, setExchangeIdOpt] = useState([])
  const [optionIdOpt, setOptionIdOpt] = useState([])

  const clearExchangeId = () => {
    form.setFieldsValue({ exchangeId: [] })
  }
  const clearOptionId = () => {
    form.setFieldsValue({ optionId: [] })
  }
  const [varietyData, setVarietyData] = useState({
    list: [],
    count: 0
  })
  const { loginStore } = useStore()
  const [params, setParams] = useState({
    pageNum: 1,
    pageSize: 20
  })


  const pageChange = (page, pageSize) => {
    setParams({
      ...params,
      pageSize: pageSize,
      pageNum: page
    })
  }
  const onSeach = (values) => {
    const _params = {
      ...values,
      exchangeId: values.exchangeId.join(','),
      optionId: values.optionId.join(','),
    }
    setParams({
      ...params,
      ..._params,
      pageNum: 1,
    })
  }

  const [tagList, setTagList] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([]) //主表里被选中的数据的 index
  // 多选
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      // console.log('1')
      // console.log('选中的key值',selectedRowKeys)
      // console.log('选中的行数据',selectedRows)
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      let temp = []
      let tempArr = []
      // 全选
      if (selected) {
        const addRow = changeRows.filter(item => {
          if (temp.indexOf(item.id) === -1) {
            temp.push(item.id)
            return true
          }
          return false
        })
        setTagList([...tagList, ...addRow])
        setSelectedRowKeys([...selectedRowKeys, ...temp])
      } else {
        // 全反选
        tempArr = [...tagList].filter(item => {
          let row = changeRows.filter(citem => item.id === citem.id)
          return !row.length
        })
        temp = tempArr.map(item => item.id)
        setTagList([...tempArr])
        setSelectedRowKeys([...temp])
      }
    },
    onSelect: (record, selected) => {
      let tempArr = [...tagList]
      let temp = [...selectedRowKeys]
      //record 返回你选中的行内容; selected 选中时返回true,取消勾选时返回false
      selected ? tempArr.push(record) : tempArr.splice(tempArr.findIndex(x => x.id === record.id), 1)
      selected ? temp.push(record.id) : temp = temp.filter(item => item !== record.id)
      setTagList(tempArr)
      setSelectedRowKeys(temp)
    },
    selectedRowKeys: selectedRowKeys, //选中的行
    getCheckboxProps: (record) => ({
      // disabled: record.id === 102
    }),
  }
  const delVariety = (row) => {
    const temp = [...selectedRowKeys].filter(item => item !== row.id)
    const list = tagList.filter(item => item.id !== row.id)
    console.log(tagList, selectedRowKeys, list, temp)
    setTagList(list)
    setSelectedRowKeys(temp)
  }
  const addVariety = async () => {
    if (addVarietyType === 1) {
      try {
        const data = {
          userId: loginStore.userId,
          groupId: props.warningroupDataRow.id,
          groupName: props.warningroupDataRow.groupAlarmName,
          featureCodes: [],
          featureTexts: [],
          poolMark: mark
        }
        const featureTextArr = featureText.split(/[\n]/)
        for (let index = 0; index < featureTextArr.length; index++) {
          const element = featureTextArr[index].trim().replace(/\s+/ig, " ")
          if (element.length) {
            const featureCodes = element.split(' ')[0].replace(/(SH)|(sh)|(Sh)|(sH)|(SZ)|(sz)|(sZ)|(Sz)/g, '')
            data.featureCodes.push(featureCodes)
            data.featureTexts.push(element.split(' ')[1])
          }
        }
        setLoading(true)
        const res = await http.post('/alarm/deliversign/addAlarmGroupFeatureByText', data)
        setLoading(false)
        message.success(res.body)
        props.changeVarietyModal(false)
      } catch (error) {
        message.error('输入的格式有误')
      }
    } else if (addVarietyType === 2) {
      if (!selectedRowKeys.length) {
        return message.warning('请勾选品种')
      }
      setLoading(true)
      const res = await http.post('/alarm/deliversign/addFeatureIntoAlarmGroupByGroupId', {
        userId: loginStore.userId,
        groupId: props.warningroupDataRow.id,
        featureIdList: selectedRowKeys,
        poolMark: mark
      })
      setLoading(false)
      message.success(res.body)
      props.changeVarietyModal(false)
    }
  }
  useEffect(() => {
    const getDicfig = async () => {
      const res = await http.post('/alarm/deliversign/getDicConfig', {
        userId: loginStore.userId,
        dictIds: [1000, 1001, 1002, 1003, 1004]
      })
      setExchangeIdOpt(res.body['1000'].map(item => ({
        label: item.dictName,
        value: item.dictCode
      })))
      setOptionIdOpt(res.body['1003'].map(item => ({
        label: item.dictName,
        value: item.dictCode
      })))
      console.log('字典-', res.body)
    }
    const getList = async () => {
      const res = await http.post('/alarm/deliversign/findFeatureInfoByPage', { userId: loginStore.userId, ...params })
      console.log('品种池列表-', res.body)
      const { list, total } = res.body
      setVarietyData({
        list: list,
        count: total
      })
    }
    if (props.showVarietymodal) {
      getList()
    } else {
      setTagList([])
      setSelectedRowKeys([])
      setAddVarietyType(1)
      setFeatureText('')
      setMark('')
    }

    if (!optionIdOpt.length) {
      getDicfig()
    }
  }, [props, params, loginStore, form, optionIdOpt])

  const columns = [
    { title: '编号', dataIndex: 'id', width: 50 },
    { title: '品种代码', dataIndex: 'scode' },
    { title: '品种名称', dataIndex: 'displayName', },
    { title: '品种市场', dataIndex: 'sgroupName', width: 100 },
    { title: '所属预警组', dataIndex: 'alarmGroupListText', width: 450 },
    // { title: '一分', dataIndex: 'mark' },
    // { title: '总分', dataIndex: 'userName' },
  ]
  const [addVarietyType, setAddVarietyType] = useState(1)
  const plainOptions = [
    { label: '文本粘贴', value: 1 },
    { label: '列表搜索', value: 2 }
  ]
  return (
    <>
      {props.showVarietymodal}
      <Modal
        forceRender
        title='添加预警组品种'
        open={props.showVarietymodal}
        onOk={handleOk}
        onCancel={handleCancel}
        width={1200}
        wrapClassName="wrapClass"
        footer={[
          <Button key="submit" type="primary" loading={loading} onClick={addVariety}>提交</Button>
        ]}
      >
        <Radio.Group
          options={plainOptions}
          onChange={(e) => setAddVarietyType(e.target.value)}
          value={addVarietyType}
          optionType="button"
          buttonStyle="solid"
          style={{ marginTop: 10 }}
        />
        {
          addVarietyType === 1 ? <>
            <Row>
              <Col span={24} >
                <div style={{ textAlign: 'center', marginBottom: 10 }}>
                  <div style={{ margin: '5px 0', fontWeight: 'bold', color: '#606266' }}>
                    {'品种代码\xa0\xa0\xa0\xa0品种名称'}
                  </div>
                  <TextArea
                    rows={15}
                    placeholder={`hc8888\xa0\xa0\xa0\xa0热轧卷板期货指数\nsp8888\xa0\xa0\xa0\xa0纸浆期货指数\nbu8888\xa0\xa0\xa0\xa0石油沥青期货指数`}
                    style={{ width: 600 }}
                    value={featureText}
                    onChange={(res) => setFeatureText(res.target.value)}
                  />
                  <div style={{ margin: '15px 0 5px 0', paddingLeft: '280px', fontWeight: 'bold', color: '#606266', textAlign: 'left' }}>
                    入池备注
                  </div>
                  <TextArea
                    rows={5}
                    placeholder='请输入备注'
                    style={{ width: 600 }}
                    value={mark}
                    onChange={(res) => setMark(res.target.value)}
                  />
                </div>
              </Col>
            </Row>
          </> : ''
        }

        <Form
          size="small"
          form={form}
          onFinish={onSeach}
          initialValues={{
            exchangeId: [],
            optionId: []
          }}
          style={{ marginTop: 15, display: addVarietyType === 2 ? 'block' : 'none' }}
        >
          <Form.Item style={{ margin: 0 }}>
            <Form.Item label="品种" name="keyWord" style={{ display: 'inline-block', width: 250, marginBottom: 10 }}>
              <Input
                allowClear
                placeholder='请输入品种名称/代码/简称'
                style={{ width: 200 }}
                onChange={form.submit}
              />
            </Form.Item>

            <Form.Item label="预警组名称" name="groupName" style={{ display: 'inline-block', width: 250, marginBottom: 10 }}>
              <Input
                allowClear
                placeholder='请输入预警组名称'
                style={{ width: 150 }}
              />
            </Form.Item>
            <Form.Item style={{ display: 'inline-block', width: 210, marginBottom: 10 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form.Item>
          <Form.Item label="品种市场" style={{ margin: 0 }}>
            <Button type="link" onClick={clearExchangeId}>不限</Button>
            <Form.Item name="exchangeId" style={{ display: 'inline-block', margin: 0 }}>
              <Checkbox.Group options={exchangeIdOpt} onChange={form.submit} />
            </Form.Item>
          </Form.Item>
          <Form.Item label="常用选项" style={{ margin: 0 }}>
            <Button type="link" onClick={clearOptionId}>不限</Button>
            <Form.Item name="optionId" style={{ display: 'inline-block', margin: 0 }}>
              <Checkbox.Group options={optionIdOpt} onChange={form.submit} />
            </Form.Item>
          </Form.Item>
        </Form>
        <Row style={{ marginTop: 20, display: addVarietyType === 2 ? 'flex' : 'none' }}>
          <Col span={19}>
            <Table
              size="small"
              rowKey="id"
              columns={columns}
              dataSource={varietyData.list}
              rowSelection={{
                type: 'checkbox',
                hideSelectAll: false,
                ...rowSelection,
              }}
              scroll={{
                y: 420,
              }}
              pagination={{
                showQuickJumper: true,
                showSizeChanger: true,
                pageSize: params.pageSize,
                onChange: pageChange,
                showTotal: (total, range) => `共 ${total} 条`,
                total: varietyData.count,
                current: params.pageNum
              }}
              bordered
            />
          </Col>
          <Col span={5}>
            <Card style={{ marginLeft: 20 }} size='small' title="已勾选" bodyStyle={{ maxHeight: 310, overflowY: 'scroll' }}>
              {tagList.map(item => (
                <div key={item.id}><Tag style={{ marginBottom: 5 }} closable onClose={() => delVariety(item)}>{item.displayName}</Tag></div>
              ))}
            </Card>
            <div style={{ marginLeft: 20 }}>
              <div style={{ margin: '5px 0 5px 0', color: '#606266', textAlign: 'left' }}>
                入池备注
              </div>
              <TextArea
                rows={5}
                placeholder='请输入备注'
                style={{ width: 600 }}
                value={mark}
                onChange={(res) => setMark(res.target.value)}
              />
            </div>
          </Col>
        </Row>
      </Modal>
    </>
  )
}

export default Setvariety